/*
 *  Menu.m
 *  pogostick
 *
 *  Loosely taken from a cocos2d-iPhone example
 *
 *  Created by daddy (chuck@kollar.com) on 8/26/09.
 *  Copyright 2009 Charles P. Kollar All rights reserved.
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

#import "Menu.h"
#import "GameLayer.h"
#import "ChipmunkPhys.h"


/**
 * The following global variables are the indexes of a menu item displayed in the
 * ConfigureMenu (implemented in the class "Layer2"). By convention the first menu
 * item is "Off" and the second is "On". In this manner these varibles will be either
 * 0 (Off) or 1 (On) depending on the selection of the user.
 */
int soundp = 1, musicp = 0;

UITextField* userNameTextField = nil;


#pragma mark -
#pragma mark MainMenu
@implementation Layer1 // SwitchTo: 0

BOOL gameStarted = NO;
BOOL resetGameOnPlay = NO;

-(id) init
{
	if( (self=[super init]) ) {
        // Build the menu, and display it...
        MenuItemImage *item1 = 
        [MenuItemImage itemFromNormalImage:(gameStarted == NO) ? @"btn-play-normal.png" : @"btn-contgame-normal.png"
                             selectedImage:(gameStarted == NO) ? @"btn-play-selected.png" : @"btn-contgame-selected.png"
                                    target:self
                                  selector:@selector(menuCallbackPlay:)];
        MenuItemImage *item2 =
        [MenuItemImage itemFromNormalImage:@"btn-savescore-normal.png" selectedImage:@"btn-savescore-selected.png"
                                    target:self selector:@selector(menuCallbackSaveScore:)];
        MenuItemImage *item3 =
        [MenuItemImage itemFromNormalImage:@"btn-highscores-normal.png" selectedImage:@"btn-highscores-selected.png"
                                    target:self selector:@selector(menuCallbackHighScores:)];
        MenuItemImage *item4 =
        [MenuItemImage itemFromNormalImage:@"btn-about-normal.png" selectedImage:@"btn-about-selected.png" 
                                    target:self selector:@selector(menuCallbackAbout:)];
        MenuItem *item5 =
        [MenuItemFont itemFromString: @"Configure" target: self selector:@selector(menuCallbackConfigure:)];
        
        Menu *menu = [Menu menuWithItems: item1, item2, item3, item4, item5, nil];
        [menu alignItemsVertically];
        
		[self addChild: menu];
	}
    
	return self;
}

//
// Because it is possible to move from the game to the menu (without the
// game being restarted) we will push and pop layers after we get to the game Layer.
// Since the game layer is conceptually, the first time, we will switch to it.
-(void) menuCallbackPlay: (id) __attribute__ ((unused)) sender
{
    if (gameStarted == NO) {
        // It is possible to get here with data from the previous game.
        // This is because we don't require the user to save the game right after
        // they win. So we check here to see if this is the case. This will
        // be the case if the "nextAboutInstruction" is "restartGame". This happens
        // when the user wins, looses, or runs out of lives. Here resetGameOnPlay
        // is set to YES and saved with the other user data...
        extern int levelNumber;
        extern int currentScore;
        extern BOOL amuletFound;
        if (resetGameOnPlay == YES) {
            resetGameOnPlay = NO;
            
            // This will start the user at the beginning...
            levelNumber = 1;
            currentScore = POINTS_PER_LIFE * START_WITH_LIVES;
            amuletFound = NO;
        }
        
        gameStarted = YES;
        
        // The first time though we add the OverLay layer to the scene
        // It is placed "on top of" the GameLayer.
        Scene *scene = [[Scene node] addChild: [GameLayer node] z:0];
        [scene addChild: [OverlayLayer node] z:1];
        
        [[Director sharedDirector] pushScene: scene];
    } else {
        [[Director sharedDirector] popScene];
    }
}

-(void) menuCallbackSaveScore:(id) __attribute__ ((unused)) sender
{
    Scene * scene = [[Scene node] addChild: [SaveScoreLayer node] z:0];
    [[Director sharedDirector] pushScene: scene];
}

-(void) menuCallbackHighScores:(id) __attribute__ ((unused)) sender
{
    Scene * scene = [[Scene node] addChild: [HighScoreLayer node] z:0];
    [[Director sharedDirector] pushScene: scene];
}

-(void) menuCallbackAbout:(id) __attribute__ ((unused)) sender {
    Scene * scene = [[Scene node] addChild: [About node] z:0];
    [[Director sharedDirector] pushScene: scene];
}

-(void) menuCallbackConfigure: (id) __attribute__ ((unused)) sender
{
    Scene * scene = [[Scene node] addChild: [Layer2 node] z:0];
    [[Director sharedDirector] pushScene: scene];
}

-(void) dealloc
{    
	[super dealloc];
}


@end

#pragma mark -
#pragma mark ConfigureMenu

@implementation Layer2

-(id) init
{
	if( (self=[super init]) ) {
        [MenuItemFont setFontName: @"American Typewriter"];
        [MenuItemFont setFontSize:18];
        MenuItemFont *title1 = [MenuItemFont itemFromString: @"Sound"];
        [title1 setIsEnabled:NO];
        [MenuItemFont setFontName: @"Marker Felt"];
        [MenuItemFont setFontSize:34];
        MenuItemToggle *item1 = [MenuItemToggle itemWithTarget:self selector:@selector(menuSoundCallback:) items:
                                 [MenuItemFont itemFromString: @"Off"],
                                 [MenuItemFont itemFromString: @"On"],
                                 nil];
        [item1 setSelectedIndex: soundp];
        
        [MenuItemFont setFontName: @"American Typewriter"];
        [MenuItemFont setFontSize:18];
        MenuItemFont *title2 = [MenuItemFont itemFromString: @"Music"];
        [title2 setIsEnabled:NO];
        [MenuItemFont setFontName: @"Marker Felt"];
        [MenuItemFont setFontSize:34];
        MenuItemToggle *item2 = [MenuItemToggle itemWithTarget:self selector:@selector(menuMusicCallback:) items:
                                 [MenuItemFont itemFromString: @"Off"],
                                 [MenuItemFont itemFromString: @"On"],
                                 nil];
        [item2 setSelectedIndex: musicp];
        
        MenuItemFont *back = [MenuItemFont itemFromString: @"--- Go Back ---" target:self selector:@selector(backCallback:)];
        
        Menu *menu = [Menu menuWithItems:
                      title1, title2,
                      item1, item2,
                      back, nil]; // 5 items.
        
        [menu alignItemsInColumns:
         [NSNumber numberWithUnsignedInt:2],
         [NSNumber numberWithUnsignedInt:2],
         [NSNumber numberWithUnsignedInt:1],
         nil
         ]; // 2 + 2 + 1 = total count of 5.
        
        [self addChild: menu];
	}
    
	return self;
}

-(void) dealloc
{
	[super dealloc];
}

-(void) menuSoundCallback: (id) sender
{
    soundp = [sender selectedIndex];
}

-(void) menuMusicCallback: (id) sender
{
    musicp = [sender selectedIndex];

}

-(void) backCallback: (id) __attribute__ ((unused)) sender
{
    [[Director sharedDirector] popScene];
	//[(MultiplexLayer*)parent switchTo:0];
}

@end


#pragma mark -
#pragma mark AboutScreens

@implementation AboutScreen

@synthesize bg;
@synthesize itemSprite;

-(id) initWithScreenFileName:(NSString *)fn
{
	if( (self=[super init]) ) {
        isTouchEnabled = YES;
        
        // Here we place the text (bg Sprite) that contains the message that we which
        // to give the user. The "Next" button are placed "overlaying this text" (z button > z bg).
        CGSize screenSize = [[Director sharedDirector] displaySize];
        
        bg = [Sprite spriteWithFile:fn];
        [bg setPosition: ccp(screenSize.height/2, screenSize.width/2)];
        [self addChild:bg z:0];
        
        itemSprite = [Sprite spriteWithFile:@"menuNext.png"];
        CGSize size = itemSprite.contentSize;
        [itemSprite setPosition: ccp(screenSize.height-size.width/2, size.height/2)];
        [self addChild:itemSprite z:1];
    }
	
	return self;
}

// Since we just have one button "next" and no scaling of the display we just look
// at the touch rather than making the thing into a menu.
-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *) __attribute__ ((unused))event nextAboutScreen:(AboutScreen *)next nextAboutInstruction:(enum nextAboutInstruction)ins
{
    CGSize screenSize = [[Director sharedDirector] displaySize];
    for (UITouch *touch in touches) {
        CGPoint loc = [touch locationInView: [touch view]];
        CGSize size = itemSprite.contentSize;
        //NSLog(@" loc:  %f,%f  size:  %f,%f\n", loc.x, loc.y, screenSize.width, screenSize.height);
        if (loc.x < size.height && loc.y > screenSize.height - size.width) {
            switch (ins) {
                case gotoScreen: {
                    // go to the next specified screen
                    Scene *scene =
                        [[Scene node] addChild: next z:0];
                    [[Director sharedDirector] replaceScene: scene];
                    break; }
                case popScreen: {
                    // go to the main menu
                    [[Director sharedDirector] popScene];
                    break; }
                case restartGame: {
                    // restart the game and go to the main menu
                    // Note: the game isn't actually restarted till the user clicks
                    // on the "Play" menu item so it is possible for them to save
                    // their score from here.

                    Scene *scene = [[Scene node] addChild: [Layer1 node] z:0];
                    [[Director sharedDirector] replaceScene: scene];
                    break; }
            }
        }
    }
}

-(void) dealloc
{
    //[bg release];
    //[itemSprite release];
    
	[super dealloc];
}

@end


@implementation About

-(id) init
{
	return [super initWithScreenFileName:@"Instructions01.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:[About1 node] nextAboutInstruction:gotoScreen];
}

@end


@implementation About1

-(id) init
{
	return [super initWithScreenFileName:@"Instructions01a.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:[About2 node] nextAboutInstruction:gotoScreen];
}

@end


@implementation About2

-(id) init
{
	return [super initWithScreenFileName:@"Instructions02.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:[About3 node] nextAboutInstruction:gotoScreen];
}

@end


@implementation About3

-(id) init
{
	return [super initWithScreenFileName:@"Instructions03.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:[About4 node] nextAboutInstruction:gotoScreen];
}

@end


@implementation About4

-(id) init
{
	return [super initWithScreenFileName:@"About.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:nil nextAboutInstruction:popScreen];
}

@end


@implementation NoMoreLives

-(id) init
{
	return [super initWithScreenFileName:@"NoMoreLives.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:nil nextAboutInstruction:restartGame];
}

@end

#if 0
//
// Called when the user wins or looses to reset the information associated with a saved game...
void resetDefaults () {
    [[NSUserDefaults standardUserDefaults] removeObjectForKey: KEY_LEVEL_NUMBER];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey: KEY_CURRENT_SCORE];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey: KEY_AMULET_FOUND];
    NSLog(@"resetDefaults... levelNumber, currentScore, amuletFound.");
}
#endif

@implementation YouWon

-(id) init
{
	return [super initWithScreenFileName:@"YouWon.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:nil nextAboutInstruction:restartGame];
}

@end


@implementation YouLost

-(id) init
{
	return [super initWithScreenFileName:@"YouLost.png"];
}

-(void)ccTouchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super ccTouchesBegan:touches withEvent:event nextAboutScreen:nil nextAboutInstruction:restartGame];
}

@end


@implementation AppController

@synthesize window;

- (void) applicationDidFinishLaunching:(UIApplication*) __attribute__ ((unused)) application
{
	// Init the window
	window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    
	// must be called before any othe call to the director
    //Director useFastDirector];
	
	// before creating any layer, set the landscape mode
	[[Director sharedDirector] setDeviceOrientation: CCDeviceOrientationLandscapeLeft];

	// show FPS (number is located at the bottom left of the screen)
	//[[Director sharedDirector] setDisplayFPS:YES];
	
	// frames per second
	[[Director sharedDirector] setAnimationInterval:1.0f/60.0f];	

	// attach cocos2d to a window
	[[Director sharedDirector] attachInView:window];
	
	// Default texture format for PNG/BMP/TIFF/JPEG/GIF images
	// It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
	// You can change anytime.
	[Texture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];	
    
	[[SimpleAudioEngine sharedEngine] preloadEffect: STICK_JUMP_WAV];
	[[SimpleAudioEngine sharedEngine] preloadEffect: STICK_HIT_PILL_WAV];
	[[SimpleAudioEngine sharedEngine] preloadEffect: GUN_FIRE_WAV];
    [[SimpleAudioEngine sharedEngine] preloadEffect: STICK_DIES_WAV];
    [[SimpleAudioEngine sharedEngine] preloadEffect: FOOT_HIT_RELEASE_WAV];
    [[SimpleAudioEngine sharedEngine] preloadEffect: PERSON_DIES_WAV];
    
	[[SimpleAudioEngine sharedEngine] playEffect: OPENING_SOUND_WAV];
    
	// seed the random generator
	srand((unsigned)[[NSDate date] timeIntervalSince1970]);
	
	// Make it look slightly prettier
	glEnable(GL_LINE_SMOOTH);
	glEnable(GL_BLEND);
	glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	glHint(GL_LINE_SMOOTH_HINT, GL_DONT_CARE);
    
	Scene *scene = [Scene node];

    //MultiplexLayer *layer = [MultiplexLayer layerWithLayers: [Layer1 node], [GameLayer node], nil];
	//[scene addChild: layer z:0];
    //[scene addChild: [OverlayLayer node] z:1];
    
    // restoring from save in "applicationWillTerminate" below....
    extern int levelNumber;
    // If the specified key does not exist, this method returns 0
    levelNumber = [[NSUserDefaults standardUserDefaults] integerForKey: KEY_LEVEL_NUMBER];
    extern int currentScore;
    currentScore = [[NSUserDefaults standardUserDefaults] integerForKey: KEY_CURRENT_SCORE];
    extern BOOL amuletFound;
    amuletFound = [[NSUserDefaults standardUserDefaults] boolForKey: KEY_AMULET_FOUND];
    resetGameOnPlay = [[NSUserDefaults standardUserDefaults] boolForKey: KEY_RESET_GAME_ON_PLAY];
    NSLog(@"applicationDidFinishLaunching Restoring... levelNumber:%d  currentScore:%d  amuletFound:%@  resetGameOnPlay:%@",
          levelNumber, currentScore, amuletFound?@"YES":@"NO", resetGameOnPlay?@"YES":@"NO");

    if (levelNumber < 1) levelNumber = 1;
    if (levelNumber == 1 && currentScore <= (POINTS_PER_LIFE * START_WITH_LIVES)) {
        currentScore = POINTS_PER_LIFE * START_WITH_LIVES;
    }
    NSLog(@"applicationDidFinishLaunching Restoring post... levelNumber:%d  currentScore:%d  amuletFound:%@  resetGameOnPlay:%@",
          levelNumber, currentScore, amuletFound?@"YES":@"NO", resetGameOnPlay?@"YES":@"NO");
    
    // Start out with the main menu screen...
    [scene addChild: [Layer1 node] z:0];

    [window setUserInteractionEnabled:YES];
	[window makeKeyAndVisible];
    
	[[Director sharedDirector] runWithScene: scene];
}

// getting a call, pause the game
-(void) applicationWillResignActive:(UIApplication *) __attribute__ ((unused)) application
{
    //NSLog(@"applicationWillResignActive\n");
    [[Director sharedDirector] pause];
}

// call got rejected
-(void) applicationDidBecomeActive:(UIApplication *) __attribute__ ((unused)) application
{
    //NSLog(@"applicationDidBecomeActive\n");
	[[Director sharedDirector] resume];
}

// purge memroy
- (void)applicationDidReceiveMemoryWarning:(UIApplication *) __attribute__ ((unused)) application {
	[[TextureMgr sharedTextureMgr] removeAllTextures];
}

// next delta time will be zero
-(void) applicationSignificantTimeChange:(UIApplication *) __attribute__ ((unused)) application
{
	[[Director sharedDirector] setNextDeltaTimeZero:YES];
}

// Set a breakpoint now for the user so that they can come back to this point if
// they need to exit the application or the iPhone decides to kill it for any reason. See...
// http://developer.apple.com/iphone/library/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/FilesandNetworking/FilesandNetworking.html
// and
// http://developer.apple.com/Mac/library/documentation/Cocoa/Reference/Foundation/Classes/NSUserDefaults_Class/Reference/Reference.html
//
- (void)applicationWillTerminate: (NSNotification *)notification
{
    // The current level number (defined in GameLayer.m GameLayer implementation)
    extern int levelNumber;
    [[NSUserDefaults standardUserDefaults] setInteger: levelNumber forKey: KEY_LEVEL_NUMBER];
    extern int currentScore;
    [[NSUserDefaults standardUserDefaults] setInteger: currentScore forKey: KEY_CURRENT_SCORE];
    extern BOOL amuletFound;
    [[NSUserDefaults standardUserDefaults] setBool: amuletFound forKey: KEY_AMULET_FOUND];
    [[NSUserDefaults standardUserDefaults] setBool: resetGameOnPlay forKey: KEY_RESET_GAME_ON_PLAY];
    NSLog(@"applicationWillTerminate Saving... levelNumber:%d  currentScore:%d  amuletFound:%@  resetGameOnPlay:%@",
          levelNumber, currentScore, amuletFound?@"YES":@"NO", resetGameOnPlay?@"YES":@"NO");
}


- (void) dealloc
{
	[window dealloc];
    
	[super dealloc];
}

@end


// The layer is set to implement the UITextFieldDelegate, UITableViewDelegate, UITableViewDataSource
@implementation SaveScoreLayer

@synthesize rootObj;
@synthesize localUsers;


UIView *oglView;
UIButton *addButton , *selButton, *cancilButton;

UILabel *aLabel;
UITextField *nameTextField;
NSString *userName;
UITableView *tableView;

//
// Event controller for adding a user that is not in the current list...
- (void) addUserButtonEvent:(id) __attribute__ ((unused)) sender
{
    UIAlertView* myAlertView =
        [[UIAlertView alloc] initWithTitle: @"Please enter your name"
                                   message: @"High Score"
                                  delegate: self 
                         cancelButtonTitle: @"Cancel" 
                         otherButtonTitles: @"Add",
         nil];
    [oglView addSubview: myAlertView];
    
    CGAffineTransform userNameTransform = CGAffineTransformMakeTranslation(0.0, 80.0);
    [myAlertView setTransform: userNameTransform];
    
    userNameTextField = [[UITextField alloc] initWithFrame: CGRectMake(12.0, 45.0, 260.0, 25.0)];
    userNameTextField.delegate = self; // set this layer as the UITextFieldDelegate
    [userNameTextField setBackgroundColor: [UIColor whiteColor]];
    [myAlertView addSubview: userNameTextField];
    [myAlertView show];
    [myAlertView release];
}

// Close the Save Score screen, and return to the page that sent us.....
-(void) menuCallback: (id) __attribute__ ((unused)) sender
{
    [aLabel removeFromSuperview];
    [tableView removeFromSuperview];
    [addButton removeFromSuperview];
    [selButton removeFromSuperview];
    [cancilButton removeFromSuperview];
    [[Director sharedDirector] popScene];
}

// Post a score to the server after the user selects a user and hits the save button...
-(void) postScore:(NSInteger) __attribute__ ((unused)) postingCategory name:(NSString *)name score:(int)score
{
	//NSLog(@"Posting Score");
    
	// Create que "post" object for the game "DemoGame 3"
	// The gameKey is the secret key that is generated when you create you game in cocos live.
	// This secret key is used to prevent spoofing the high scores
	ScoreServerPost *server = [[ScoreServerPost alloc] initWithGameName:GAME_NAME gameKey:GAME_KEY delegate:self];
    
	NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithCapacity:2];
    
	// cc_ files are predefined cocoslive fields.
    
    //[dict setObject:GAME_NAME forKey:@"cc_gamename"];
    
	// set score
	[dict setObject: (NSInteger)[NSNumber numberWithInt:score ] forKey:@"cc_score"];
    
	// set playername
	[dict setObject:name forKey:@"cc_playername"];
    
	// cc_ are fields that cannot be modified. cocos fields
	// set category... it can be "easy", "medium", whatever you want.
	[dict setObject:GAME_CATEGORY forKey:@"cc_category"];
	
	//NSLog(@"Sending data: %@", dict);
    
	// You can add a new score to the database
    //	[server sendScore:dict];
	
	// Or you can "update" your score instead of adding a new one.
	// The score will be udpated only if it is better than the previous one
	// 
	// "update score" is the recommend way since it can be treated like a profile
	// and it has some benefits like: "tell me if my score was beaten", etc.
	// It also supports "world ranking". eg: "What's my ranking ?"
	[server updateScore:dict];
	
	// Release. It won't be freed from memory until the connection fails or suceeds
	[server release];
}

#pragma mark -
#pragma mark ScorePost Delegate

// Callbacks for PostScore...

-(void) scorePostOk: (id) sender
{
	//NSLog(@"score post OK");
	if( [sender ranking] != kServerPostInvalidRanking && [sender scoreDidUpdate]) {
		NSString *message = [NSString stringWithFormat:@"World ranking: %d", [sender ranking]];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Post Ok."
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:nil
                                              otherButtonTitles:@"OK",
                              nil];	
		alert.tag = 2;
		[alert show];
		[alert release];
	}
    [self menuCallback: nil]; // Win or loose we return from this menu item
}

-(void) scorePostFail: (id) sender
{
	NSString *message = nil;
	tPostStatus status = [sender postStatus];
	if( status == kPostStatusPostFailed )
		message = @"Cannot post the score to the server. Retry";
	else if( status == kPostStatusConnectionFailed )
		message = @"Internet connection not available. Enable wi-fi / 3g to post your scores to the server";
	
	//NSLog(@"%@", message);
    
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Score Post Failed"
                                                    message:message
                                                   delegate:nil
                                          cancelButtonTitle:nil
                                          otherButtonTitles:@"OK",
                          nil];	
	alert.tag = 0;
	[alert show];
	[alert release];
    [self menuCallback: nil]; // Win or loose we return from this menu item
}

// The user clicking on the save button is what starts the score being posted...
- (void) saveButtonEvent:(id) __attribute__ ((unused)) sender
{
    // open a alert with an OK and cancel button because of this feedback from trying to sumbit the application on the app store
    //
    // Your application, Adventures of Mr. Pogostick, cannot be posted to the App Store because it violates section 3.3.6 of the iPhone Developer Program License Agreement:
    //
    // Any form of user or device data collection, or image, picture or voice capture or recording performed by the Application (collectively “Recordings”),
    // and any form of user data, content or information processing, maintenance, uploading, syncing, or transmission performed by the Application (collectively 
    // "Transmissions") must comply with all applicable privacy laws and regulations as well as any Apple program requirements related to such aspects, including 
    // but not limited to any notice or consent requirements. In particular, a reasonably conspicuous audio, visual, or other indicator must be displayed to the 
    // user as part of the Application to indicate that a Recording is taking place."
    //
    // Please make it clear to the user that their personal user data is being uploaded to your server, and obtain their consent before submission.
    extern int currentScore;

    NSString *message =
      [NSString stringWithFormat:@"The selected User name and Score (%d) will be uploaded to the Internet World High Score Board Server for all to see!", currentScore];
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Privacy Warning"
                                                    message:message
                                                    delegate:self 
                                                    cancelButtonTitle:@"Cancel"
                                                    otherButtonTitles:@"OK", nil];
    [alert show];
    [alert release];
}


- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
    //NSLog(@"alertView: buttonIndex: %d", buttonIndex);
    if (buttonIndex == 1) {
        extern int currentScore;
        //NSLog(@"ok");
        NSIndexPath *ip = [tableView indexPathForSelectedRow];
        if (ip != nil) {
            UITableViewCell *cell = [tableView cellForRowAtIndexPath: ip];
            userName = cell.textLabel.text;
            //NSLog(@"saveButtonEvent Posting Score for name '%s' score: %d\n", [userName UTF8String], currentScore);
            [self postScore:[NSNumber numberWithInt:kCategoryHard] name:userName score:currentScore];
        }
    } else {
        // indexButton == 0
        //NSLog(@"cancel");
    }
}



//// UITextFieldDelegate methods...
// When the user taps in a text field, that text field becomes the first responder
// and automatically asks the system to display the associated keyboard.
// Here the resignFirstResponder message removes the keyboard.
// In theory you can check the content of the field to see if it contains valid data,
// alert the user and ignore this return (e.g. not remove the keyboard).
// This is enabled by assigning this object as the delegate for this UITextField
// see "UITextField Protocol Reference"
// http://developer.apple.com/iphone/library/documentation/UIKit/Reference/UITextFieldDelegate_Protocol/UITextFieldDelegate/UITextFieldDelegate.html#//apple_ref/occ/intf/UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    
    // This does not seem to be getting called... ????
    if ([[textField text] length] == 0) {
        return NO;
    }
    NSEnumerator *enumerator = [localUsers objectEnumerator];
    NSString *element;
    while (element = [enumerator nextObject]) {
        if ([element isEqualToString: [textField text]]) {
            return NO;
        }
    }
        
    [textField resignFirstResponder];
    return YES;    
}


///
// methods for reading and writing property lists...

- (NSData *)copyApplicationDataFromFile:(NSString *)fileName { 
    NSArray *paths =
        NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    NSData *myData = [[NSData alloc] initWithContentsOfFile:appFile];
    return myData;
}

- (id)copyApplicationPlistFromFile:(NSString *)fileName {
    NSData *retData;
    NSString *error;
    id retPlist;
    NSPropertyListFormat format;
    
    retData = [[self copyApplicationDataFromFile: fileName] autorelease];
    if (!retData) {
        //NSLog(@"applicationPlistFromFile: Data file not returned.");
        return nil;
    }

    retPlist = [NSPropertyListSerialization
                    propertyListFromData: retData
                    mutabilityOption: NSPropertyListImmutable
                    format: &format
                    errorDescription :&error];
    if (!retPlist){
        //NSLog(@"applicationPlistFromFile: Plist not returned, error: %@", error);
    }
    // make a mutable copy for us to work with...
    //NSLog(@"retPlist  %@ %@", [retPlist class], retPlist); 
    NSMutableDictionary *retMPlist = [retPlist mutableCopy];
    //NSLog(@"retMPlist  %@ %@", [retMPlist class], retMPlist); 
    //[retPlist release];
    return retMPlist;
}

- (BOOL)writeApplicationData:(NSData *)data toFile:(NSString *)fileName {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                         NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    if (!documentsDirectory) {
        //NSLog(@"Documents directory not found!");
        return NO;
    }
    NSString *appFile = [documentsDirectory stringByAppendingPathComponent:fileName];
    return [data writeToFile:appFile atomically:YES];
}

- (BOOL)writeApplicationPlist:(id)plist toFile:(NSString *)fileName {
    NSString *error;
    NSData *pData = [NSPropertyListSerialization
                        dataFromPropertyList: plist
                        format: NSPropertyListBinaryFormat_v1_0
                        errorDescription: &error];
    if (!pData) {
        //NSLog(@"writeApplicatinPlist: %@", error);
        return NO;
    }
    return [self writeApplicationData: pData toFile: fileName];
}

// dump the property list to the console...
-(void) dumpPropsToLog: (NSDictionary *)rd {
    for (id key in rd) {
        NSDictionary *props = [rd objectForKey:key];
        for (id key2 in props) {
            NSLog(@"key: %@, prop: %@  value: %@", key, key2, [props objectForKey:key2]);
        }
    }
}

// Write an initial entry to game data file...
// THERE MIGHT BE A MEMORY LEAK HERE THE TWO NSARRAY!!!!!!
-(void) addNewUserEntry: (NSMutableDictionary *)rd name:(NSString*)name score:(int)score {
    NSDictionary *dict = [NSDictionary
                          dictionaryWithObjects:
                          [NSArray arrayWithObjects: [NSNumber numberWithInt:score], [NSNumber numberWithInt:1], nil]
                          forKeys:
                          [NSArray arrayWithObjects:@"HighScore", @"Games", nil]
                          ];
    [rd setObject:dict forKey:name];
}

// This method is called after the text field resigns its first responder status.
// You can use this method to update your delegate’s state information.
- (void)textFieldDidEndEditing:(UITextField *)textField {
    userName = [textField text];
    //NSLog(@"textFieldDidEndEditing name: %s\n", [userName UTF8String]);
    // add this user name to the list in the table
    [localUsers addObject: [textField text]];  
    [tableView reloadData];
    
    [self addNewUserEntry: rootObj name: [textField text] score: 0];
    [self writeApplicationPlist: rootObj toFile: GAME_DATA_FILE_NAME];
}


//
// UITableView delegate methods for the users local to this device...

- (NSInteger)numberOfSectionsInTableView:(UITableView *) __attribute__ ((unused)) tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *) __attribute__ ((unused)) tableView numberOfRowsInSection:(NSInteger) __attribute__ ((unused)) section {
	return [localUsers count];
}

- (NSString *)tableView:(UITableView *) __attribute__ ((unused)) tableView titleForHeaderInSection:(NSInteger) __attribute__ ((unused)) section {
    // The header for the section is the region name -- get this from the region at the section index.
    //NSString *key = [localUsers objectAtIndex:section];
    return @"Select User then Save";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *MyIdentifier = @"MyIdentifier";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
    if (cell == nil) {
        cell = [[UITableViewCell alloc]
                 initWithStyle:UITableViewCellStyleDefault
                 reuseIdentifier:MyIdentifier];
		cell.selectionStyle = UITableViewCellSelectionStyleBlue;
    }
#if 0==0
    if (indexPath.row == 0 || indexPath.row%2 == 0) {
        UIColor *altCellColor = [UIColor colorWithWhite:0.7 alpha:0.1];
        cell.backgroundColor = altCellColor;
    }
#endif
    cell.textLabel.text = [localUsers objectAtIndex:[indexPath row]];
    //cell.detailTextLabel.text = @"999";

    return cell;
}

- (void)tableView:(UITableView*) __attribute__ ((unused)) tableView didSelectRowAtIndexPath:(NSIndexPath *) __attribute__ ((unused)) indexPath {
    [selButton setEnabled: YES];
}
- (void)tableView:(UITableView*) __attribute__ ((unused)) tableView didDeselectRowAtIndexPath:(NSIndexPath *) __attribute__ ((unused)) indexPath {
    [selButton setEnabled: NO];
}

-(id) init
{ 
	if( (self=[super init]) ) {
        oglView = [[Director sharedDirector] openGLView];
        
        CGRect frame4 = CGRectMake(200.0, 40.0, 100.0, 30.0);
        addButton = [[UIButton alloc] initWithFrame:frame4];
        UIImage *buttonImage = [UIImage imageNamed:@"btn-adduser-normal.png"];
        [addButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
        buttonImage = [UIImage imageNamed:@"btn-adduser-selected.png"];
        [addButton setBackgroundImage:buttonImage forState:UIControlStateSelected];
        addButton.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        addButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        addButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [addButton addTarget:self
                      action:@selector(addUserButtonEvent:) 
            forControlEvents:UIControlEventTouchUpInside];
        // then add the button to a UIView like this:
        [oglView addSubview: addButton];
       
        CGRect frame5 = CGRectMake(150.0, 40.0, 100.0, 30.0);
        selButton = [[UIButton alloc] initWithFrame:frame5];
        buttonImage = [UIImage imageNamed:@"btn-save-normal.png"];
        [selButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
        buttonImage = [UIImage imageNamed:@"btn-save-selected.png"];
        [selButton setBackgroundImage:buttonImage forState:UIControlStateSelected];
        selButton.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        selButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        selButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [selButton addTarget:self
                      action:@selector(saveButtonEvent:) 
            forControlEvents:UIControlEventTouchUpInside];
        // then add the button to a UIView like this:
        [selButton setEnabled: NO];
        [oglView addSubview: selButton];
        
        CGRect frame6 = CGRectMake(30.0, 40.0, 100.0, 30.0);
        cancilButton = [[UIButton alloc] initWithFrame:frame6];
        //[cancilButton setTitle:@"Cancil" forState:UIControlStateNormal];
        //cancilButton.backgroundColor = [UIColor greenColor];
        //[cancilButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //[cancilButton setTitleColor:[UIColor blackColor] forState:UIControlEventTouchDown];
        buttonImage = [UIImage imageNamed:@"btn-goback-normal.png"];
        [cancilButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
        buttonImage = [UIImage imageNamed:@"btn-goback-selected.png"];
        [cancilButton setBackgroundImage:buttonImage forState:UIControlStateSelected];
        cancilButton.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        cancilButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        cancilButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [cancilButton addTarget:self
                      action:@selector(menuCallback:) 
            forControlEvents:UIControlEventTouchUpInside];
        // then add the button to a UIView like this:
        [oglView addSubview: cancilButton];
        
        // 250, 40, 110, 280
        // Place this above the nameTextField
        CGRect frame = CGRectMake(190, 120, 240, 200);
        aLabel = [[[UILabel alloc] initWithFrame:frame] autorelease];
        aLabel.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        aLabel.textAlignment = UITextAlignmentCenter;
        aLabel.backgroundColor = [UIColor clearColor];
        aLabel.font = [UIFont systemFontOfSize:18.0];
        aLabel.userInteractionEnabled = NO;
        aLabel.textColor = [UIColor whiteColor];
        aLabel.text = @"Save to World High Scores";
        [oglView addSubview: aLabel];

        // read in the property list and make the array of users...
        rootObj = [self copyApplicationPlistFromFile: GAME_DATA_FILE_NAME];

        //[self dumpPropsToLog: rootObj];
        // If this is the first time...
        if (rootObj == nil) {
            rootObj = [[NSMutableDictionary dictionaryWithCapacity:1] retain];
            [nameTextField becomeFirstResponder];
        }
        
        localUsers = [[NSMutableArray alloc] init];
        for (id key in rootObj) {
            [localUsers addObject: key];
        }
        
        CGRect frame3 = CGRectMake(40, 115, 220, 240);
        tableView = [[UITableView alloc] initWithFrame:frame3 style:UITableViewStylePlain];
        tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        tableView.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        tableView.delegate = self;
        tableView.dataSource = self;
        [oglView addSubview: tableView];
        [tableView reloadData];
    }
    return self;
}

#pragma mark -
#pragma mark Init
-(void) dealloc
{
    [localUsers release];
    [rootObj release];
    
    [super dealloc];
}

@end


#pragma mark -
#pragma mark HighScoresScreen

@implementation HighScoreLayer

@synthesize globalScores;
@synthesize tableView;

enum {
	kCellHeight = 24,
};

enum {
    kName = 1,
    kScore = 2,
    kPosition = 3,
    kFlag = 4,
    kSpeed = 5,
    kAngle = 6
};

UIView *oglView;


// http://developer.apple.com/iphone/library/documentation/UserExperience/Conceptual/TableView_iPhone/TableViewCells/TableViewCells.html

#pragma mark UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *) __attribute__ ((unused)) tableView {
	return 1;
}

-(CGFloat) tableView:(UITableView *) __attribute__ ((unused)) tableView heightForRowAtIndexPath:(NSIndexPath *) __attribute__ ((unused)) indexPath
{
	return kCellHeight;
}

- (NSInteger)tableView:(UITableView *) __attribute__ ((unused)) tableView numberOfRowsInSection:(NSInteger) __attribute__ ((unused)) section 
{
	///AppController *appDelegate = [[UIApplication sharedApplication] delegate];
	NSInteger i = [globalScores count];
	
	return i;
}

- (NSString *)tableView:(UITableView *) __attribute__ ((unused)) tableView titleForHeaderInSection:(NSInteger) __attribute__ ((unused)) section {
    return @"World High Scores";
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
	static NSString *MyIdentifier = @"HighScoreCell";
	
	UILabel *name, *score, *idx;//, *country, *speed, *angle;
	
	UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
	if (cell == nil) {
		cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:MyIdentifier] autorelease];
		
        // Position
		idx = [[UILabel alloc] initWithFrame:CGRectMake(0.0f, 0.0f, 24, kCellHeight-2)];
		idx.tag = kPosition;
		//		name.font = [UIFont boldSystemFontOfSize:16.0];
		idx.font = [UIFont fontWithName:@"Marker Felt" size:16.0f];
		idx.adjustsFontSizeToFitWidth = YES;
		idx.textAlignment = UITextAlignmentRight;
		idx.textColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f];
		idx.autoresizingMask = UIViewAutoresizingFlexibleRightMargin; 
		[cell.contentView addSubview:idx];
		[idx release];
		
		// Name
		name = [[UILabel alloc] initWithFrame:CGRectMake(65.0f, 0.0f, 150, kCellHeight-2)];
		name.tag = kName;
		//		name.font = [UIFont boldSystemFontOfSize:16.0];
		name.font = [UIFont fontWithName:@"Marker Felt" size:16.0f];
		name.adjustsFontSizeToFitWidth = YES;
		name.textAlignment = UITextAlignmentLeft;
		name.textColor = [UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f];
		name.autoresizingMask = UIViewAutoresizingFlexibleRightMargin; 
		[cell.contentView addSubview:name];
		[name release];
		
		// Score
		score = [[UILabel alloc] initWithFrame:CGRectMake(200, 0.0f, 70.0f, kCellHeight-2)];
		score.tag = kScore;
		score.font = [UIFont systemFontOfSize:16.0f];
		score.textColor = [UIColor darkGrayColor];
		score.adjustsFontSizeToFitWidth = YES;
		score.textAlignment = UITextAlignmentRight;
		score.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
		[cell.contentView addSubview:score];
		[score release];
#if 0	
		// Speed
		speed = [[UILabel alloc] initWithFrame:CGRectMake(65, 20.0f, 40.0f, kCellHeight-2)];
		speed.tag = kSpeed;
		speed.font = [UIFont systemFontOfSize:16.0f];
		speed.textColor = [UIColor darkGrayColor];
		speed.adjustsFontSizeToFitWidth = YES;
		speed.textAlignment = UITextAlignmentRight;
		speed.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
		[cell.contentView addSubview:speed];
		[speed release];
		
		// Angle
		angle = [[UILabel alloc] initWithFrame:CGRectMake(160, 20.0f, 35.0f, kCellHeight-2)];
		angle.tag = kAngle;
		angle.font = [UIFont systemFontOfSize:16.0f];
		angle.textColor = [UIColor darkGrayColor];
		angle.adjustsFontSizeToFitWidth = YES;
		angle.textAlignment = UITextAlignmentRight;
		angle.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
		[cell.contentView addSubview:angle];
		[angle release];
		
		// Flag
		country = [[UILabel alloc] initWithFrame:CGRectMake(280, 20.0f, 16, kCellHeight-2)];
		country.tag = kFlag;
		country.font = [UIFont systemFontOfSize:16.0f];
		country.textColor = [UIColor darkGrayColor];
		country.adjustsFontSizeToFitWidth = YES;
		country.textAlignment = UITextAlignmentRight;
		country.autoresizingMask = UIViewAutoresizingFlexibleRightMargin;
		[cell.contentView addSubview:country];
		[country release];
#endif
	} else {
        idx = (UILabel *)[cell.contentView viewWithTag:kPosition];
		name = (UILabel *)[cell.contentView viewWithTag:kName];
		score = (UILabel *)[cell.contentView viewWithTag:kScore];
#if 0
		speed = (UILabel *)[cell.contentView viewWithTag:kSpeed];
		angle = (UILabel *)[cell.contentView viewWithTag:kAngle];
        country = (UILabel*)[cell.contentView viewWithTag:kFlag];
#endif   
	}
	int r = [indexPath row];
    id s = [globalScores objectAtIndex: r];
    
	idx.text = [[s objectForKey:@"position"] stringValue];
	name.text = [s objectForKey:@"cc_playername"];
	// this is an NSNumber... convert it to string
	score.text = [[s objectForKey:@"cc_score"] stringValue];
#if 0
	speed.text = [[s objectForKey:@"usr_speed"] stringValue];
	angle.text = [[s objectForKey:@"usr_angle"] stringValue];
	country.text = [s objectForKey:@"cc_country"];
#endif
    // This doesn't appear to work. From the articles it appears that you need to subclass
    // the TableViewCell to get this to work.
    if (indexPath.row == 0 || indexPath.row%2 == 0) {
        UIColor *altCellColor = [UIColor colorWithRed: 0.0 green: 0.0 blue: 0.1 alpha: 0.1];
        cell.backgroundColor = altCellColor;
    }

	return cell;
}

-(void) requestScore
{
	//NSLog(@"Requesting scores...");
    
	ScoreServerRequest *request = [[ScoreServerRequest alloc] initWithGameName:GAME_NAME delegate:self];
    
	// The only supported flags as of v0.2 is kQueryFlagByCountry and kQueryFlagByDevice
	tQueryFlags flags = kQueryFlagIgnore;
	if( world == kCountry )
		flags = kQueryFlagByCountry;
	else if(world == kDevice )
		flags = kQueryFlagByDevice;
    
	// request All time Scores: the only supported version as of v0.2
	// request best 15 scores (limit:15, offset:0)
	[request requestScores:kQueryAllTime limit:15 offset:0 flags:flags category:GAME_CATEGORY];
    
	// Release. It won't be freed from memory until the connection fails or suceeds
	[request release];
}

#pragma mark -
#pragma mark ScoreRequest Delegate

-(void) scoreRequestOk: (id) sender
{
	//NSLog(@"score request OK");	
	NSArray *scores = [sender parseScores];	
	NSMutableArray *mutable = [NSMutableArray arrayWithArray:scores];
    if (globalScores != nil) [globalScores release];
	globalScores = [mutable retain];
	[tableView reloadData];
}

-(void) scoreRequestFail: (id) __attribute__ ((unused)) sender
{
	//NSLog(@"score request fail");
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Score Request Failed" message:@"Internet connection not available, cannot view world scores" delegate:nil cancelButtonTitle:nil otherButtonTitles:@"OK", nil];	
	alert.tag = 0;
	[alert show];
	[alert release];	
}

-(void) menuCallback: (id) __attribute__ ((unused)) sender
{
    [tableView removeFromSuperview];
    [cancilButton removeFromSuperview];
    [[Director sharedDirector] popScene];
}

-(id) init
{ 
	if( (self=[super init]) ) {
        oglView = [[Director sharedDirector] openGLView];
        
        CGRect frame1 = CGRectMake(30.0, 40.0, 100.0, 30.0);
        cancilButton = [[UIButton alloc] initWithFrame:frame1];
        //[cancilButton setTitle:@"Cancil" forState:UIControlStateNormal];
        //cancilButton.backgroundColor = [UIColor Color];
        //[cancilButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        //[cancilButton setTitleColor:[UIColor blackColor] forState:UIControlEventTouchDown];
        UIImage *buttonImage = [UIImage imageNamed:@"btn-goback-normal.png"];
        [cancilButton setBackgroundImage:buttonImage forState:UIControlStateNormal];
        buttonImage = [UIImage imageNamed:@"btn-goback-selected.png"];
        [cancilButton setBackgroundImage:buttonImage forState:UIControlStateSelected];
        cancilButton.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        cancilButton.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
        cancilButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        [cancilButton addTarget:self
                         action:@selector(menuCallback:) 
               forControlEvents:UIControlEventTouchUpInside];
        // then add the button to a UIView like this:
        [oglView addSubview: cancilButton];
        
        CGRect frame2 = CGRectMake(40, 130, 280, 240);
        tableView = [[UITableView alloc] initWithFrame:frame2 style:UITableViewStylePlain];
        tableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
        tableView.transform = CGAffineTransformMakeRotation(M_PI * (90.0 / 180.0));
        tableView.delegate = self;
        tableView.dataSource = self;
        [oglView addSubview: tableView];
        //[tableView reloadData];
        
        globalScores = [[NSMutableArray alloc] init];
        category = kCategoryEasy;
        world = kAll;
        
        // requestScore will result in scoreRequestOK being called
        // At this point "globalScores" contains a "NSMutableArray" containing the scores.     
        [self requestScore];
    }
    return self;
}

- (void) dealloc
{
    [globalScores release];
    [tableView release];
    
	[super dealloc];
}


@end
